import GameStateSystem from "../gameStateSystem";
import GameInput from "../../gameplay/gameInput";
import GameButton from "../../gameplay/input/gameButton";
import PillState, { SmallPillState } from "../pillState";
import Pill, { BigPill, SmallPill } from "./pill";
import { createCanvas } from "../../canvas";

export default class PlayScene {
  private gameStateSystem = new GameStateSystem();
  private pills: Pill<PillState>[] = [];
  private nowPill: Pill<PillState>;
  private context2d: CanvasRenderingContext2D;
  private isPause = true;

  constructor() {
    const canvas = createCanvas({
      id: 'canvas1',
      width: 128,
      height: 128,
      scalePixel: true,
    });
    const context2d = canvas.getContext('2d');
    context2d.font = '14px pixel';
    context2d.fillStyle = '#fafafa';
    this.context2d = context2d;
    document.body.appendChild(canvas);

    GameInput.onButton((button: GameButton, isPressed: boolean) => {
      if (isPressed) {
        this.gameStateSystem.applyButtonInput(button);
        if (button == GameButton.Ok) {
          this.isPause = !this.isPause;
        }
      }
    });
    this.gameStateSystem.pillCreated.add((pillState) => {
      console.log('create', pillState.value);
      if (this.nowPill == null && this.isPause) {
        this.isPause = false;
      }
      if (pillState instanceof SmallPillState) {
        this.nowPill = new SmallPill();
      } else {
        this.nowPill = new BigPill();
      }
      this.nowPill.pillState = pillState;
      this.nowPill.ctx = context2d;
      this.pills.push(this.nowPill);
    });
    this.gameStateSystem.pillDeleted.add((pillState) => {
      console.log('delete', pillState.value);
      this.pills = this.pills.filter((pill) => pill.pillState != pillState);
    });
    this.gameStateSystem.pillReplaced.add((pillState) => {
      const pill = new SmallPill();
      pill.pillState = pillState;
      pill.ctx = context2d;
      this.pills.push(pill);
    });
    this.gameStateSystem.start();
  }

  update() {
    if (this.isPause) {
      return;
    }
    this.gameStateSystem.update();
    //document.body.innerText = this.stateSystem.board.toString();
  }

  draw() {
    if (this.isPause) {
      return;
    }
    this.context2d.clearRect(0, 0, 128, 128);
    if (this.nowPill) {
      this.nowPill.pillState = this.gameStateSystem.controlledPill;
      this.nowPill.draw();
    }
    this.pills.forEach((pill) => {
      if (this.nowPill != pill) {
        pill.draw();
      }
    });
  }
}